<template>
  <div class="news">
    <div>
      <el-row>
        <el-col :offset="20">
          <el-button type="primary"
                     @click="addNewsVisible=true" class="add">新增</el-button>
        </el-col>
      </el-row>
    </div>

    <el-table :data="tableData" style="width: 1500px"
              :header-cell-style="{background:'#fdfdfd',color:'#409eff',textAlign: 'center'}"
              :cell-style="{ textAlign: 'center' }">
      <el-table-column prop="title" label="新闻标题" width="200"/>
      <el-table-column prop="pictureUrl" label="图片" width="550">
        <template  v-slot="scope">
          <img class="img" style="width:100%" :src="scope.row.pictureUrl" alt />
        </template>
      </el-table-column>

      <el-table-column prop="content" label="新闻简介"  width="500">
        <template v-slot="scope" >
          <p>{{scope.row.content}}</p>
        </template>
      </el-table-column>

      <el-table-column prop="operation" label="操作"  width="250">
        <template v-slot="scope">
          <el-button type="primary" @click="openedit(scope.row.id)">编辑</el-button>

          <el-popconfirm
              confirm-button-text="是"
              cancel-button-text="否"
              :icon="InfoFilled"
              icon-color="#626AEF"
              title="是否确定删除?"
              @confirm="del(scope.row.id)"
          >
            <template #reference>
              <el-button type="danger" >删除</el-button>
            </template>
          </el-popconfirm>
        </template>
      </el-table-column>
    </el-table>

  </div>
<!--增加新闻-->
  <el-dialog
      v-model="addNewsVisible"
      title="新增新闻" width="60%"
      align-center
      class="dialog"
  >

    <el-form
        :model="addForm"
        ref="addForm"
        :rules="addRule"
    >
      <el-form-item label="标题" prop="title" >
        <el-input v-model="addForm.title"  placeholder="新闻标题"/>
      </el-form-item>
      <el-form-item label="简介"  prop="workdesc">
        <el-input v-model="addForm.workdesc"  type="textarea" placeholder="新闻简介"  />
      </el-form-item>
      <el-form-item label="网页" prop="url">
        <el-input v-model="addForm.url"  type="textarea" placeholder="新闻url"  />
      </el-form-item>
      <el-form-item class="bottom-but" label="封面" prop="fileList" >
        <el-upload
            class="uploadFile"
            action="http://120.48.51.66:8081/news/addNews"
            :on-preview="handlePreview"
            :on-remove="handleRemove"
            :before-remove="beforeRemove"
            multiple

            accept="image/jpg,image/jpeg,image/png"


            :on-change="handChange"
            :on-exceed="handleExceed"
            :auto-upload="false"
            :file-list="addForm.fileList"
            show-file-list
        >
          <el-button size="small" type="primary">点击上传</el-button>
        </el-upload>

      </el-form-item>

    </el-form>


    <template #footer>
      <span>
        <el-button class="cancel-but" @click="addNewsVisible=false">取消</el-button>
          <el-button type="primary" @click="makeSure" >确认</el-button>
      </span>
    </template>
  </el-dialog>

<!--修改新闻-->
  <el-dialog
      v-model="editNewsVisible"
      title="编辑新闻" width="60%"
      align-center
      class="dialog"
  >

    <el-form
        :model="editForm"
        ref="editForm"
        :rules="editRule"
    >
      <el-form-item label="标题" prop="title"  >
        <el-input v-model="editForm.title" placeholder="请输入将要修改为的新闻标题"/>
      </el-form-item>
      <el-form-item label="简介" prop="workdesc">
        <el-input v-model="editForm.workdesc"  type="textarea" placeholder="请输入将要修改为的新闻简介"  />
      </el-form-item>

      <el-form-item class="bottom-but" label="封面" prop="fileList0" >
        <el-upload
            class="uploadFile"
            action="http://120.48.51.66:8081/news/editNews"
            :on-preview="handlePreview0"
            :on-remove="handleRemove0"
            :before-remove="beforeRemove0"
            multiple
            accept="image/jpg,image/webp,image/png"


            :limit="1"
            :on-change="handChange0"
            :on-exceed="handleExceed0"
            :auto-upload="false"
            :file-list="editForm.fileList0"
            show-file-list
        >
          <el-button size="small" type="primary">点击上传</el-button>
        </el-upload>

      </el-form-item>

    </el-form>




    <template #footer>
      <span>
        <el-button class="cancel-but" @click="editNewsVisible=false">取消</el-button>
          <el-button type="primary" @click="editSure" >确认</el-button>
      </span>
    </template>
  </el-dialog>

</template>

<script >
// import  { UploadProps } from 'element-plus'
import axios from "axios";
import {ElMessage} from "element-plus";

export default {
  name:'app',
  inject:['reload'],
  created(){
    console.log('成功加载数据')
    this.getdata()
  },
  setup(){
    let checkUrl  = (rule, value, callback) => {
      if(!value){
        return callback(new Error('Url不能为空!'))
      } else {
        var strRegex = '^((https|http|ftp|rtsp|mms)?://)'
            + '?(([0-9a-z_!~*\'().&=+$%-]+: )?[0-9a-z_!~*\'().&=+$%-]+@)?' //ftp的user@
            + '(([0-9]{1,3}.){3}[0-9]{1,3}' // IP形式的URL- 199.194.52.184
            + '|' // 允许IP和DOMAIN（域名）
            + '([0-9a-z_!~*\'()-]+.)*' // 域名- www.
            + '([0-9a-z][0-9a-z-]{0,61})?[0-9a-z].' // 二级域名
            + '[a-z]{2,6})' // first level domain- .com or .museum
            + '(:[0-9]{1,4})?' // 端口- :80
            + '((/?)|' // a slash isn't required if there is no file name
            + '(/[0-9a-z_!~*\'().;?:@&=+$,%#-]+)+/?)$';
        var re=new RegExp(strRegex);
        //re.test()
        if (re.test(value)) {
          return callback();
        } else {
          return callback(new Error("url不正确"));
        }
      }
    }
    return{
      checkUrl
    }
  },
  data(){
    return{
      newsId:'',

      tableData:[ ],
      addNewsVisible:false,
      editNewsVisible:false,
      addForm:[
        {
          title:'',
          workdesc:'',
          url:'',
          fileList:[],
        }
      ],
      addRule:{
        title: [
          {required: true,trigger:'blur' ,message:'请输入标题'}
        ],
        workdesc: [
          {required: true,trigger:'blur' ,message:'请输入简介'}
        ],
        url: [
          {required: true,trigger:'blur' ,message:'请输入网页url'},
          { validator: this.checkUrl, trigger: "blur" }
        ],
        fileList:[
          {required: true,trigger:'blur' ,message:'请上传图片'}
        ]
      },
      currentFile:[],
      currentFile0:[],


      editForm:[
        {
          title:'',
          workdesc:'',
          fileList0:[],
        }
      ],
      editRule:{
        title: [
          {required: true,trigger:'blur' ,message:'请输入标题'}
        ],
        workdesc: [
          {required: true,trigger:'blur' ,message:'请输入简介'}
        ],
        fileList0:[
          {required: true,trigger:'blur' ,message:'请上传图片'}
        ]
      },

    }
  },

  methods:{
    getdata(){
      axios.get('http://120.48.51.66:8081/news/getNews'
          ,{
            params:{

            }
          }).then((response)=>{
        if(response.data.code==200){

          console.log('新闻数据')
          this.tableData=response.data.data.newsList
         // this.reload();
        }else{
          this.$message({
            message: "获取新闻列表失败",
            type: "error"
          });
        }
      })


    },
openedit(temp){
  this.newsId=temp
  this.editNewsVisible=true
},
    edit(){
      //调用后端函数传入temp
      let form=new FormData()
      form.append("id",this.newsId)
      form.append("title", this.editForm.title)
      form.append("content",this.editForm.workdesc)
      form.append("multipartFile", this.editForm.fileList0[0].raw)
      axios.post('http://120.48.51.66:8081/news/editNews',form).then( (response)=>{
        if(response.data.code==200){
          ElMessage({
            message:"编辑成功",
            type:'success'
          });
          console.log('编辑成功')
          this.reload()
        }else if(response.data.code==19000){
          this.$message({
            message: "请上传正确图片格式",
            type: "error"
          });
        }

        else{

          this.$message({
            message: "编辑失败",
            type: "error"
          });
        }
      });


    },
    editSure(){
      this.$refs.editForm.validate(valid=>{
            if(valid)
            {
              console.log('兜底成功')
              this.edit()
              this.editNewsVisible=false;
            }else{
              console.log('兜底失败')
            }
          }
      )
    },


    del(temp){
      // alert('删除'+temp)
      //调用后端函数传入temp
      let form=new FormData();
      form.append("id",temp)
      axios.post('http://120.48.51.66:8081/news/deleteNews',form).then( (response)=>{
        if(response.data.code==200){
          ElMessage({
            message:"删除新闻成功",
            type:'success'
          });
          this.reload()
          console.log('删除新闻成功')
        }else{
          this.$message({
            message: "删除新闻失败",
            type: "error"
          });
        }
      });
    },

    addNews(){
      console.log('添加新闻')
      // console.log(this.fileList[0].raw)
      let form=new FormData()
      form.append("title", this.addForm.title)
      form.append("content",this.addForm.workdesc)
      form.append("multipartFile", this.addForm.fileList[0].raw)
      form.append("url", this.addForm.url)

      axios.post('http://120.48.51.66:8081/news/addNews',form).then( (response)=>{

        if(response.data.code==200){
          ElMessage({
            message:"添加成功",
            type:'success'
          });
          console.log('添加成功')
          console.log(form)
          this.reload()
        }else if(response.data.code==19000){
          this.$message({
            message: "请上传正确图片格式",
            type: "error"
          });
        }else{
          this.$message({
            message: "添加失败",
            type: "error"
          });
        }
      });

    },
    makeSure(){
      this.$refs.addForm.validate(valid=>{
            if(valid)
            {
              console.log('兜底成功')
              this.addNews()
              this.addNewsVisible=false
            }else{
              console.log('兜底失败')
            }
          }
      )
    },

    handleRemove(file, fileList) {
      console.log(file, fileList);
    },
    handlePreview(file) {
      console.log(file);
    },
    handChange(file,fileList){
      //一旦选中文件，就将该文件添加到currentFile中
      this.currentFile.push(file)
      this.addForm.fileList=fileList
      console.log(fileList[0].raw)
    },
    handleExceed() {
      this.$message.warning('只能上传1个文件哦');
    },
    beforeRemove(file) {
      return this.$confirm(`您确定要移除 ${ file.name }吗？`);
    },







    handleRemove0(file, fileList) {
      console.log(file, fileList);
    },
    handlePreview0(file) {
      console.log(file);
    },
    handChange0(file,fileList){
      //一旦选中文件，就将该文件添加到currentFile中
      this.currentFile0.push(file)
      this.editForm.fileList0=fileList
      console.log(fileList[0].raw)
    },
    handleExceed0() {
      this.$message.warning('只能上传1个文件哦');
    },
    beforeRemove0(file) {
      return this.$confirm(`您确定要移除 ${ file.name }吗？`);
    },



  }

}
</script>

<style>
.add{
  position: relative;
  top: -15px;
  left: 108px;
}
.img{
  width:200px;
  height: 300px;
}
.avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

</style>
